package service.Impl;

import dao.role_per.SysPermissionDao;
import dao.role_per.PermSiteDao;
import entity.PermSite;
import entity.SysAccounts;
import entity.SysPermission;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.SysPermissionService;
import vo.SysMenuVo;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 权限(SysPermission)表服务实现类
 *
 * @author liujh
 * @since 2020-08-10 16:59:20
 */
@Service("sysPermissionService")
@Slf4j
public class SysPermissionServiceImpl implements SysPermissionService {


    @Autowired
    private SysPermissionDao sysPermissionDao;



    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SysPermission queryById(Long id) {
        return this.sysPermissionDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<SysPermission> queryAllByLimit(int offset, int limit) {
        return this.sysPermissionDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param sysPermission 实例对象
     * @return 实例对象
     */
    @Override
    public SysPermission insert(SysPermission sysPermission) {
        this.sysPermissionDao.insert(sysPermission);
        return sysPermission;
    }

    /**
     * 修改数据
     *
     * @param sysPermission 实例对象
     * @return 实例对象
     */
    @Override
    public SysPermission update(SysPermission sysPermission) {
        this.sysPermissionDao.update(sysPermission);
        return this.queryById(sysPermission.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.sysPermissionDao.deleteById(id) > 0;
    }


    @Override
    public Set<String> queryPerm(Long userId) {

        return this.sysPermissionDao.findByList(userId);
    }

    @Override
    public List<SysMenuVo> queryByList() {
        SysAccounts accounts = (SysAccounts) SecurityUtils.getSubject().getPrincipal();
        List<SysMenuVo> permissionList = sysPermissionDao.queryList(accounts.getUserId());
        List<SysMenuVo> menuVoList = new ArrayList<>();
        for (SysMenuVo po: permissionList) {
            /*SysMenuVo vo = new SysMenuVo();
             BeanUtils.copyProperties(po,vo);*/
            if (0==po.getParentId()){
                menuVoList.add(po);
            }
            List<SysMenuVo> childrenList = new ArrayList<>();
            for (SysMenuVo node: permissionList) {
                if (Long.toString(node.getParentId()).equals(Long.toString(po.getId()))){
                    childrenList.add(node);
                }
            }
            po.setChildrenList(childrenList);
        }
        return menuVoList;
    }
}